package com.senven.order.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPayUtil;
import com.senven.common.entity.Branch;
import com.senven.common.entity.Order;
import com.senven.common.entity.PayOrder;
import com.senven.common.entity.User;
import com.senven.common.utils.WebUtils;
import com.senven.common.utils.HttpClient;
import com.senven.common.vo.CommonResult;
import com.senven.order.config.AliPayConfig;
import com.senven.order.config.OrderRandom;
import com.senven.order.mapper.OrderMapper;
import com.senven.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wt
 * @since 2022-08-31
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderRandom orderRandom;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public CommonResult findOrderByUserid(String userid) {
        List<Order> list = orderMapper.findOrderByUseid(userid);
        if (list!=null){
            return new CommonResult(2000,"查询成功",list);
        }
        return new CommonResult(5000,"查询失败",null);
    }

    @Override
    public CommonResult findOrderByOrderId(String orderid) {
        List<Order> list = orderMapper.findOrderByOrderId(orderid);

        List<Order> totallist = orderMapper.findOrderByOrderIdToTal(orderid);


        if (list!=null){
            Map<String,List<Order>> map = new HashMap();
            map.put("list",list);
            map.put("totallist",totallist);
            return new CommonResult(2000,"查询成功",map);
        }
        return new CommonResult(5000,"查询失败",null);
    }


    @Transactional
    @Override
    public CommonResult backFindAllOrder(Integer currentPage, Integer pageSize, Map map) {

        //通过token获取用户id---通过用户id查询角色id---判读如果角色id=2则通过用户id查询店铺id并将店铺id传给查询所有
        //获取登录者的roleid,通过roleid判断是商家还是管理员
        HttpServletRequest result = WebUtils.getResult();
        String token = result.getHeader("token");
        Map map1 = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        Map user = (Map) map1.get("user");
        String id = (String) user.get("id");
        Integer roleid = orderMapper.selectRoleId(id);
        map.put("branchid",null);
        if (roleid==2){
            Integer branchid = orderMapper.selectBranchId(id);
            map.put("branchid",branchid);
        }
        map.put("roleid",roleid);
        PageHelper.startPage(currentPage,pageSize);
        List<Order> list = orderMapper.backFindAllOrder(map);
        if (list!=null){
            PageInfo<Order> pageInfo = new PageInfo(list);
            return new CommonResult(2000,"查询成功",pageInfo);
        }
        return new CommonResult(5000,"查询失败",null);


    }

    @Override
    public CommonResult orderFindOrderByOrderId(Integer currentPage, Integer pageSize, Map map) {
        PageHelper.startPage(currentPage,pageSize);
        System.out.println(map);

        Object s =  map.get("orderId");
        String orderid = String.valueOf(s);
        List<Order> list = orderMapper.findOrderByOrderId(orderid);
        if (list!=null){
            PageInfo<Branch> pageInfo = new PageInfo(list);
            return new CommonResult(2000,"查询成功",pageInfo);
        }
        return new CommonResult(5000,"查询失败",null);
    }

    //购物车-----远程调用的订单方法
    @Override
    @Transactional
    public String insertOrder(Order order) {
        String sss = orderRandom.sss();
        order.setOrders(sss);
        int i= orderMapper.insert(order);

        String orderId = orderMapper.selectOrderId(order.getOrders());
//        String s = String.valueOf(orderId);
        int i1 = orderMapper.insertUserByOrder(orderId,order.getUserId());

        List<PayOrder> orderList = order.getOrderList();


        for (PayOrder xxx:orderList){
            xxx.setOrderId(orderId);

            int j1 = orderMapper.insertUserByGoods(xxx);
        }
//        PayOrder payOrder = new PayOrder();
//        int gid = 0;
//        List<PayOrder> list = new ArrayList<>();
//        for (PayOrder xx:orderList) {
//            list.add(xx);
//            if (xx.getGid()==gid){
//                xx.
//            }
//            gid = xx.getGid();
//        }

        if (i>0){
            return sss;
        }
        return "-1";

    }

    @Override
    public CommonResult createNavite(String orders) {

        //根据订单号查询订单信息
        QueryWrapper wrapper = new QueryWrapper();
        //订单号
        wrapper.eq("orders",orders);

        //订单状态
        wrapper.eq("status",0);
        Order order = orderMapper.selectOne(wrapper);
        Integer branchid = order.getBranchid();
        if(order!=null){
            try {
                //创建HttpClient对象 远程调用
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //开启支持https协议
                client.setHttps(true);
                //设置请求的参数  XML格式
                Map<String,String> param = new HashMap<>();
                param.put("appid",appId);
                param.put("mch_id",mchId);
                param.put("nonce_str", WXPayUtil.generateNonceStr());
                param.put("body","点菜");
                param.put("out_trade_no",orders);
                //0.01为测试金额
                //param.put("total_fee",new BigDecimal(order.getTotalFee()).multiply(new BigDecimal(100)).longValue()+"");
                param.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
                //可以换成项目部署的ip
                param.put("spbill_create_ip","127.0.0.1");
                param.put("notify_url","http://localhost:9000/pay/back");
                param.put("trade_type","NATIVE");
                System.out.println(param);
                client.setXmlParam(WXPayUtil.generateSignedXml(param,apiKey));
                //发送请求
                client.post();
                //获取请求的响应结果
                String content = client.getContent();

                Map<String, String> map = WXPayUtil.xmlToMap(content);
                if(map.get("result_code").equals("SUCCESS")){
                    Map<String,Object> result = new HashMap<>();
                    result.put("codeUrl",map.get("code_url"));
                    result.put("price",order.getTotal());
                    result.put("orders",orders);
                    return new CommonResult(2000,"生成二维码成功",result);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return new CommonResult(5000,"订单失效",null);
    }

    @Override
    public CommonResult queryPayStutus(String orders) {
        try{
            //根据订单状态查询微信的支付情况
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            Map<String,String> params = new HashMap<>();
            params.put("appid",appId);
            params.put("mch_id",mchId);
            params.put("out_trade_no",orders);
            params.put("nonce_str",WXPayUtil.generateNonceStr());

            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
            client.post();

            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if(map.get("trade_state").equals("SUCCESS")){
                //修改订单状态
                Order order = new Order();
                order.setStatus(1);
                //order.setPlaceTime(LocalDateTime.now());
                //order.setPlaceTime(LocalDateTime.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                QueryWrapper<Order> wrapper = new QueryWrapper<>();
                wrapper.eq("orders",orders);
                wrapper.eq("status",0);
                orderMapper.update(order,wrapper);
                return new CommonResult(2000,"支付成功",null);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new CommonResult(5000,"支付失败",null);
    }

    @Override
    public CommonResult updateOrderStatus(Order order) {

        int update = orderMapper.updateById(order);
        if (update>0){
            return new CommonResult(2000,"发货成功",null);
        }
        return  new CommonResult(5000,"发货失败",null);
    }
}























